#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
FlaSam Code

2007 2007-6-24 上午07:57:04
'''

from apps.ad_usergroup.models import AdPlace
from apps.ad_usergroup.models import AdPlayerInfo
from apps.ad_usergroup.models import AdUserProfile
from django.contrib.auth.models import User
from django.db import models
from middleware import threadlocals_middleware
from urllib import quote
from utils import ad_utils
from django.db.models.fields.related import OneToOneField


# Create your models here.

#===============================================================================
# class AdApproval(models.Model):
#    pass
#===============================================================================


#===============================================================================
# class AdItemInfoManager(models.Manager):
#    
#    def get_useable_item(self):
#        return self.filter(ad_item_useable_state=True).values()
#    
#    def get_unuseable_item(self):
#        return self.filter(ad_item_useable_state=False).values()
#    
#    def get_approved_item(self):
#        return self.filter(ad_item_approve_state=True).values()
#    
#    def get_disapproved_item(self):
#        return self.filter(ad_item_approve_state=False).values()
#===============================================================================

#class AdItemManager(models.Manager):
#    
#    def get_item(self):
#        p = self.ad_item_protocol
#        
#        if p == 'wallpaper':
#            return super()
#        else:
#            return None
    
AD_ITEM_PROTOCOL_CHOICES = (
                       ('wallpaper', u'桌面壁纸'), \
                       ('syspopurl', u'系统启动后弹出IE窗口'), \
                       ('homepage', u'IE主页'), \
                       ('activedesktop', u'Active Desktop'), \
                       ('desktopshortcuturl', u'桌面快捷方式'), \
                       #('application', u'系统启动后运行程序')
                       )

AD_ITEM_DISPLAY_INTERVAL_CHOICES = (
                             (0, '随机时间播放'), \
                             (10, '每隔十分钟切换'), \
                             (20, '每隔二十分钟切换'), \
                             (30, '每隔三是分钟切换')
                             )

class AdItemInfo(models.Model):
    '''
    广告信息
    '''
    
    ad_item_name = models.CharField(verbose_name='名称', \
                                    help_text='广告条目的名称', \
                                    max_length=16, \
                                    blank=False)
    
    ad_item_useable = models.BooleanField(verbose_name='是否可用', \
                                          help_text='该广告条目是否可用', \
                                          default=False)
    
    ad_item_desc = models.TextField(verbose_name='说明', \
                                    help_text='该广告条目的说明', \
                                    blank=True)
    
    ad_item_uuid = models.CharField(max_length=38, \
                                    default='', \
                                    editable=False, \
                                    blank=True, \
                                    unique=True)
    
    ad_item_protocol = models.CharField(verbose_name='广告播放协议', \
                                        help_text='除桌面壁纸和ActiveDesktop外将不受播放间隔影响', \
                                        choices=AD_ITEM_PROTOCOL_CHOICES, \
                                        max_length=256)
    
    creator = models.ForeignKey(User, \
                                null=True, \
                                blank=False, \
                                related_name='ad_item_creator', \
                                editable=False)
    
    last_modify_by = models.ForeignKey(User, \
                                       null=True, \
                                       blank=True, \
                                       verbose_name='最后的修改者', \
                                       help_text='该条目的最后修改者', \
                                       related_name='aditem_last_modify_by', \
                                       editable=False)
    
    last_modify_datetime = models.DateTimeField(auto_now=True, \
                                                verbose_name='最后修改时间')
    
    ad_item_display_interval = models.SmallIntegerField(verbose_name='广告切换间隔', \
                                                        help_text='只针对桌面壁纸, ActiveDesktop, IE主页 起作用', \
                                                        choices=AD_ITEM_DISPLAY_INTERVAL_CHOICES) 
    
    ad_item_create_datetime = models.DateTimeField(verbose_name='广告条目的创建日期时间', \
                                                   auto_now_add=True, \
                                                   editable=False)
    
    ad_item_start_date = models.DateField(verbose_name='开始播放日期', \
                                              help_text='该广告条目的开始播放日期, 该日期不能晚于结束时间', \
                                              blank=False)
    
    ad_item_expire_date = models.DateField(verbose_name='结束播放日期', \
                                               help_text='该广告条目的结束播放时间, 该日期不能早于开始时间', \
                                               blank=False, null=True)
    
    def get_item(self):
        p = self.ad_item_protocol
        
        if p == 'wallpaper':
            return self.aditemwallpaper
        elif p == 'syspopurl':
            return self.aditemsyspopurl
        elif p == 'homepage':
            return self.aditemhomepage
        elif p == 'activedesktop':
            return self.aditemactivedesktop
        elif p == 'desktopshortcuturl':
            return self.aditemdesktopshortcuturl
        else:
            return None
    
    def get_protocol(self):
        return self.ad_item_protocol
    
    def get_protocol_display(self):
        return self.get_ad_item_protocol_display()
     
#    objects = AdItemManager()
    
    def save(self):
        if self.ad_item_uuid == '':
            self.ad_item_uuid = ad_utils.mk_uuid()
        else:
            pass
        
        # auto creator and last_modify_by 
        if self.id and threadlocals_middleware.get_current_user() != None:
            self.last_modify_by = threadlocals_middleware.get_current_user()
        else:
            if self.creator:
                self.last_modify_by = self.creator
            else:
                self.creator = self.last_modify_by = threadlocals_middleware.get_current_user()                                                                                      
        super(AdItemInfo, self).save()
        
#    def get_ad_item_uuid(self):
#        return self.ad_uuid
#    
#    def get_qoute_ad_item_uuid(self):
#        return quote(self.ad_uuid)
    
    def __unicode__(self):
        return self.ad_item_name
    
    class Admin:
        list_display = ('ad_item_name', \
                        'ad_item_uuid', \
                        'ad_item_protocol', \
                        )
        
    class Meta:
        permissions = (
                       ('can_add_aditem', u'允许 创建 广告条目'), \
                       ('can_del_aditem', u'允许 删除 广告条目'), \
                       ('can_edit_aditem', u'允许 编辑 广告条目'), \
                       ('can_approve_aditem', u'允许 审核 广告条目'), \
                       ('can_change_aditem_expire', u'允许 修改 广告条目过期时间')
                       )

class AdItemWallpaper(models.Model):
    
    ad_item_name = models.OneToOneField(AdItemInfo)
    ad_wallpaper = models.ImageField(verbose_name='桌面图片', help_text='图片尺寸为 1024x768', upload_to='upload/%Y/%m/%d')
    
    def __str__(self):
        return self.get_ad_wallpaper_url()
    
    class Admin:
        list_display = ('ad_item_name', 'ad_wallpaper')
        
class AdItemSyspopurl(models.Model):
    
    ad_item_name = models.OneToOneField(AdItemInfo)
    ad_item_url = models.URLField(verify_exists=False)
    
    def __str__(self):
        return self.ad_item_url
    
    class Admin:
        list_display = ('ad_item_name', 'ad_item_url')
        
class AdItemHomepage(models.Model):
    
    ad_item_name = models.OneToOneField(AdItemInfo)
    ad_item_url = models.URLField(verify_exists=False)
    
    def __str__(self):
        return self.ad_item_url
    
    class Admin:
        list_display = ('ad_item_name', 'ad_item_url')
        
class AdItemActivedesktop(models.Model):
    
    ad_item_name = models.OneToOneField(AdItemInfo)
    ad_item_url = models.URLField(verify_exists=False)
    
    def __str__(self):
        return self.ad_item_url
    
    class Admin:
        list_display = ('ad_item_name', 'ad_item_url')
        
class AdItemDesktopshortcuturl(models.Model):
    
    ad_item_name = OneToOneField(AdItemInfo)
    ad_item_filename = models.CharField(max_length=1024)
    ad_item_url = models.URLField(verify_exists=False)
    
    def __str__(self):
        return self.ad_item_url
    
    class Admin:
        list_display = ('ad_item_name', 'ad_item_url', 'ad_item_filename')
    
#class AdItemApplication(models.Model):
#    
#    ad_item_name = OneToOneField(AdItemInfo)
#    ad_item_filename = models.CharField(max_length=1024)
#    ad_item_filepath = models.CharField(max_length=1024)
#    
#    def __str__(self):
#        import os.path
#        return os.path.join(self.ad_item_filepath, self.ad_item_filename)
#    
#    class Admin:
#        list_display = ('ad_item_name', 'ad_item_filename', 'ad_item_filepath')

class AdOrganizeInfo(models.Model):
    
    creator = models.ForeignKey(User, \
                                      null=True, \
                                      blank=True, \
                                      related_name='adorg_creator', \
                                      verbose_name='创建者', \
                                      help_text='该广告的创建者', \
                                      editable=False)
    last_modify_by = models.ForeignKey(User, \
                                       null=True, \
                                       blank=True, \
                                       verbose_name='最后的修改者', \
                                       help_text='该条目的最后修改者', \
                                       related_name='adorg_last_modify_by', \
                                       editable=False)
    last_modify_datetime = models.DateTimeField(auto_now=True, \
                                                verbose_name='最后修改时间')
    adorg_auto_desc = models.CharField(max_length=512, \
                                       blank=True, \
                                       default='', \
                                       editable=False, \
                                       verbose_name='系统描述', \
                                       help_text='系统自动生成的描述')
    adorg_desc = models.TextField(blank=True, \
                                  default='', \
                                  verbose_name='描述', \
                                  help_text='自定义描述')
    adorg_uuid = models.CharField(max_length=38, \
                                  default=ad_utils.NULL_UUID, \
                                  editable=False, \
                                  blank=True, \
                                  unique=True, \
                                  null=True, \
                                  verbose_name='UUID')
    
    def __unicode__(self):
        return self.adorg_auto_desc
    
    def save(self):
        
        # auto creator and last_modify_by 
        if self.id and threadlocals_middleware.get_current_user() != None:
            self.last_modify_by = threadlocals_middleware.get_current_user()
        else:
            if self.creator:
                self.last_modify_by = self.creator
            else:
                self.creator = self.last_modify_by = threadlocals_middleware.get_current_user()
            
            # we make a temp uuid , aftet save item , will be remake a new namespace uuid
            #self.adorg_uuid = ad_utils.mk_uuid()
            
        super(AdOrganizeInfo, self).save()
    
    class Admin:
        list_display = ('creator', 'last_modify_by', 'last_modify_datetime', 'adorg_auto_desc', 'adorg_uuid')


class AdOrganize(models.Model):
    '''
     TAG: To define a many-to-one relationship that can have a null foreign key, use ForeignKey() with null=True .

    投放广告用户或者区域的编组

    '''

    info = models.OneToOneField(AdOrganizeInfo)
    
    users = models.ManyToManyField(AdPlayerInfo, \
                                  null=True, \
                                  blank=True, \
                                  verbose_name='播放者', \
                                  help_text='广告的定点播放者')
    
    places = models.ManyToManyField(AdPlace, \
                                   null=True, \
                                   blank=True, \
                                   verbose_name='播放地区', \
                                   help_text='广告的播放地区')
    
    def flush_adorg_info(self):
        p = self.places.all()
        u = self.users.all()
        
        self.info.adorg_uuid = ad_utils.mk_name_space_uuid('%s%s' % (u, p))

        if u.count() == 0 and p.count() == 0:
            self.info.adorg_auto_desc = u"投放广告区域: [ 所有区域 ]; 投放广告用户: [ 所有用户 ]"
        elif u.count() == 0 and p.count() != 0:
            _place_name = []
            for x in p:
                _place_name.append(u'%s' % x)
            self.info.adorg_auto_desc = u"投放广告区域: [ %s ]; 投放广告用户: [ 所有用户 ]" % ' , '.join(_place_name)
        elif u.count() != 0 and p.count() != 0:
            _place_name = []
            for x in p:
                _place_name.append(u'%s' % x)
            _user_name = []
            for x in u:
                _user_name.append('%s' % x)
            self.info.adorg_auto_desc = u"投放广告区域: [ %s ];  投放广告用户: [ %s ]" % (' , '.join(_place_name), ' | '.join(_user_name))
        elif u.count() != 0 and p.count() == 0:
            _user_name = []
            for x in u:
                _user_name.append('%s' % x.username)
            self.info.adorg_auto_desc = u'投放广告区域: [ 所有区域 ]; 投放广告用户: [ %s ]' % ' , '.join(_user_name)
        else:
            self.info.adorg_auto_desc = '生成自动描述错误!!!'
                
        self.info.save()
        
    def save(self):
        super(AdOrganize, self).save()
        
    def __str__(self):
        return str(self.info)
    
    class Meta:
        permissions = (
                       ('can_add_adorg', u'允许 创建 广告条目编组'), \
                       ('can_edit_adorg', u'允许 编辑 广告条目编组'), \
                       ('can_del_adorg', u'允许 删除 广告条目编组')
                       )
    class Admin:
        pass
        
#dispatcher.connect( post_save_agorg , signal=signals.post_save, sender=AdOrganize )     
#print dispatcher.liveReceivers(dispatcher.getReceivers(sender=dispatcher.Any, signal=dispatcher.Any))
#dispatcher.connect(post_add_agorg , signal=ad_signals.post_add, sender=AdOrganize)

#===============================================================================
# dispatcher.connect( post_delete_adorg , signal=signals.post_delete, sender=AdOrganize )
#===============================================================================


class AdPushManager(models.Manager):
    
    def get_userable_push(self):
        return self.filter(ad_push_useable_state=True).values()
    
    def get_unuseable_push(self):
        return self.filter(ad_push_useable_state=False).values()
    
    def get_expired_push(self):
        pass
    
    def get_unexpired_push(self):
        pass
    
#AD_PUSHGROUP_LEVEL_CHOICES = (
#                      (0, u'不显示'), \
#                      (2, u'最低'), \
#                      (4, u'较低'), \
#                      (6, u'中等'), \
#                      (8, u'较高'), \
#                      (10, u'最高'), \
#                      (12, u'总是显示')
#                      )

class AdPush(models.Model):
    '''
    广告的最终投放信息
    
    客户端提交 useruuid 之后在 AdOrganize 查询是否被编组，
    如果没有被编组，则查询时候有相同的place被编组，如果以上都没有则显示默认广告编组
    
    桌面壁纸,使用特定的属性,顺序或者随机播放,其他类型依次播放
    
    每个投放信息,只关联一个广告条目,但是可以管理多个编组,
    投放应该以广告条目为中心
    '''
    
    ad_push_name = models.CharField(max_length=256, blank=False)
    ad_push_desc = models.TextField(blank=True)
    
    ad_push_start_date = models.DateField()
    ad_push_expire_date = models.DateField()
    
    ad_push_organize = models.ManyToManyField(AdOrganizeInfo, verbose_name='广告编组')
    #ad_push_level = models.SmallIntegerField(choices=AD_PUSHGROUP_LEVEL_CHOICES, default=0)
    
    ad_push_creator = models.ForeignKey(AdUserProfile, related_name='ad_push_creator', blank=False)
    ad_push_useable_state = models.BooleanField(default=False)
    
    ad_push_approver = models.ForeignKey(AdUserProfile, related_name='ad_push_approver', blank=True, null=True)
    ad_push_reject_reason = models.TextField(default='', blank=True)
    
    ad_push_uuid = models.CharField(max_length=38, default='', editable=False, blank=True, unique=True)
    
    #ad_item = models.ManyToManyField(AdItemInfo)
    ad_item = models.ForeignKey(AdItemInfo, blank=False, verbose_name='广告条目', help_text='投放的广告条目')
    
    objects = AdPushManager()
    
    def save(self):
        if self.ad_push_uuid == '':
            self.ad_push_uuid = ad_utils.mk_uuid()
        else:
            pass
        super(AdPush, self).save()
        
    def __str__(self):
        return self.ad_push_name
    
    class Meta:
        permissions = (
                       ('can_add_adpush', u'允许 创建 广告推送条件'), \
                       ('can_edit_adpush', u'允许 编辑 广告推送条件'), \
                       ('can_del_adpush', u'允许 删除 广告推送条件'), \
                       ('can_approve_adpush', u'允许 审核 广告推送条件'), \
                       ('can_change_adpush_expire', u'允许 修改 广告推送时间')
                       )
    
    class Admin:
        list_display = ('ad_push_name', \
                        'ad_push_start_date', \
                        'ad_push_expire_date', \
                        'ad_push_creator', \
                        'ad_push_uuid'
                        )
